import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { Card, Descriptions, Button, Spin, message } from 'antd';
import axios from 'axios';

function ScriptDetail() {
  const { id } = useParams();
  const [script, setScript] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchScriptDetail = async () => {
      try {
        const response = await axios.get(`http://localhost:5000/api/scripts/${id}`);
        setScript(response.data);
        setLoading(false);
      } catch (error) {
        console.error('Error fetching script detail:', error);
        message.error('获取剧本详情失败');
        setLoading(false);
      }
    };

    fetchScriptDetail();
  }, [id]);

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!script) {
    return <div>剧本不存在</div>;
  }

  return (
    <div>
      <Link to="/">
        <Button style={{ marginBottom: 16 }}>返回列表</Button>
      </Link>

      <Card title={`剧本详情: ${script.name}`} bordered={false}>
        <Descriptions bordered column={2}>
          <Descriptions.Item label="ID">{script._id}</Descriptions.Item>
          <Descriptions.Item label="上传时间">
            {new Date(script.createdAt).toLocaleString()}
          </Descriptions.Item>
          <Descriptions.Item label="剧本简介" span={2}>
            {script.description || '暂无简介'}
          </Descriptions.Item>
          <Descriptions.Item label="BGM文件">
            {script.bgmUrl ? (
              <audio controls src={`http://localhost:5000${script.bgmUrl}`}></audio>
            ) : (
              '暂无BGM'
            )}
          </Descriptions.Item>
        </Descriptions>

        <div style={{ marginTop: 20 }}>
          <h3>剧本内容预览</h3>
          <pre style={{ 
            backgroundColor: '#f5f5f5', 
            padding: '16px', 
            borderRadius: '4px',
            maxHeight: '400px',
            overflow: 'auto'
          }}>
            {script.content ? script.content.substring(0, 1000) + '...' : '暂无内容'}
          </pre>
        </div>
      </Card>
    </div>
  );
}

export default ScriptDetail;